use std::error::Error;
use std::fs;
use std::env;


pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

impl Config {
    pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments.");
        }

        println!("{:?}",args.next());

        // 多使用了一些内存，但是减少管理生命周期的步骤
        // let query = args[1].clone();
        // let filename = args[2].clone();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string")
        };

        println!("query: {}",query);

        let filename = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query filename")
        };

        println!("filename: {}",filename);

        println!("{:?}",env::var("CASE_SENSITIVE"));

        let case_sensitive = env::var("CASE_SENSITIVE").is_err();

        println!("{}",case_sensitive);

        Ok(Config { query, filename, case_sensitive })
    }
}

pub fn run (config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;

    let results = if config.case_sensitive {
        search(&config.query, &contents)
    } else {
        search_case_insensitive(&config.query, &contents)
    };

    for content in results {
        println!("{}",content);
    }
    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    // let mut results = Vec::new();
    //
    // for line in contents.lines() {
    //     if line.contains(query) {
    //         results.push(line);
    //     }
    // }
    // results

    contents.lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    // let mut results = Vec::new();
    // let query = query.to_lowercase();
    //
    // for line in contents.lines() {
    //     if line.to_lowercase().contains(&query) {
    //         results.push(line);
    //     }
    // }
    // results

    contents.lines()
        .filter(|line| line.to_lowercase()
            .contains(query)).collect()
}

#[cfg(test)]
mod  tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
        Rust:\
        safe, fast, produtive.\
        Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query,contents))
    }


}